import 'dart:convert';
import 'dart:typed_data';

import 'package:crypto/crypto.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:keyboard_utils_fork/keyboard_listener.dart' as key_listener;
import 'package:keyboard_utils_fork/keyboard_utils.dart';

import 'package:package_info/package_info.dart';

import '../../bean/login_entity.dart';
import '../../config/ApiConfig.dart';
import '../../config/GlobalConfig.dart';
import '../../config/RouteConfig.dart';
import '../../http/DioClient.dart';
import '../../http/core/ResponseData.dart';
import '../../http/hd_http.dart';
import '../../util/HDNavigator.dart';
import '../../util/LoadingUtils.dart';
import '../../util/cache_util.dart';
import '../../view/dialog/dialog_manager.dart';
import 'state.dart';

class LoginNewLogic extends GetxController {
  final LoginNewState state = LoginNewState();
  KeyboardUtils _keyboardUtils = KeyboardUtils();
  int _idKeyboardListener = 0;

  selUser() async{
    List userItems = [
      {"name": "13888888888", "code": "123456"},
      {"name": "13777777777", "code": "123456"},
    ];
    var user = await DialogManager.showActionSheet(items: userItems, title: "选择人");
    if(user != null){
      state.controllerName.text = user["name"] ?? "";
      state.controllerPsd.text = user["code"] ?? "";
    }
  }

  @override
  void onClose() {
    super.onClose();
    _keyboardUtils.unsubscribeListener(subscribingId: _idKeyboardListener);
    if (_keyboardUtils.canCallDispose()) {
      _keyboardUtils.dispose();
    }
  }

  @override
  void onReady() {
    super.onReady();
    _idKeyboardListener = _keyboardUtils.add(
        listener: key_listener.KeyboardListener(willHideKeyboard: () {
      FocusManager.instance.primaryFocus?.unfocus();
    }, willShowKeyboard: (d) {

    }));

    if (CacheUtil().get<String>("userName")?.isNotEmpty == true) {
      state.controllerName.text = CacheUtil().get<String>("userName") ?? "";
    }
    if (CacheUtil().get<String>("password")?.isNotEmpty == true) {
      state.controllerPsd.text = CacheUtil().get<String>("password") ?? "";
    }

    PackageInfo.fromPlatform().then((value) {
      state.version = value.version;
      GlobalConfig.version = value.version;
      update();
    });
  }


  void requestLogin() async {
    if(state.controllerName.text.isEmpty){
      LoadingUtils.showToast("请输入用户名");
      return;
    }
    if(state.controllerPsd.text.isEmpty){
      LoadingUtils.showToast("请输入登录密码");
      return;
    }

    Uint8List content = Utf8Encoder().convert(state.controllerPsd.text);
    Digest digest = md5.convert(content);

    Map<String, dynamic> map = {
      "loginName": state.controllerName.text,
      "password": state.controllerPsd.text,
    };
    ResponseData response = await DioClient().doPost(ApiConfig.login, data: map);
    if (response.isok) {
      if(response.code == "0"){
        /// 本地保存token
        CacheUtil().setJson(GlobalConfig.LoginJson, response.data);
        CacheUtil().setString("userName", state.controllerName.text);
        CacheUtil().setString("password", state.controllerPsd.text);
        LoginEntity entity = LoginEntity.fromJson(response.data);
        GlobalConfig.loginEntity = entity;
        HDNavigator.offAllNamed(RouteConfig.main);
      }else {
        LoadingUtils.showToast(response.msg??"登录失败");
      }
    } else {
      LoadingUtils.showToast(response.msg??"登录失败");
    }
  }

  int times = 0;

  ///表示按照点击处理选择网络情况
  void dealHideNetClick(){
    if (kDebugMode) {
      choseNetWork();
      return;
    }
    if (times == 0 && ApiConfig.currentNetWork == "pro") {
      times++;
      Future.delayed(
        const Duration(seconds: 9),
        () => times = 0,
      );
    } else {
      times++;
      if (times > 10 || ApiConfig.currentNetWork != "pro") {
        if (ApiConfig.currentNetWork != "pro") {
          times = 0;
        }
        choseNetWork();
      }
    }
  }
  choseNetWork() async{
    /// 此时弹框可以选择网络
    var itemlist = ApiConfig.listNetWork
        .map((e) => {
      "code": e["code"],
      "name": e["code"] == ApiConfig.currentNetWork ? "当前网络:${e["name"]}" : e["name"]
    })
        .toList();
    var sheetitem = await DialogManager.showActionSheet(
        title: "请选择网络", items: itemlist, displayKey: "name");
    if (sheetitem != null) {
      //ApiConfig.currentNetWork = sheetitem["code"];
      CacheUtil().setString("cacheNetWork",sheetitem["code"]);
    }
  }
}
